#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import re
import json
import logging
from utils import utils_data, ErrorInfoBuilder

logger = logging.getLogger('my_logger')


def check_hvigor():
    pattern = re.compile(r'(\bohos_[a-z_]+_suite)\("([^"]+)"\)\s*\{')
    file_entities = utils_data.get_file()

    has_error = False
    hvigor_templates = ['ohos_js_app_suite', 'ohos_app_assist_suite']
    no_hvigor_templates = ['ohos_hap_assist_suite', 'ohos_js_hap_suite']

    for file_entity in file_entities:
        if file_entity.file_name == 'BUILD.gn':
            file_path = file_entity.full_path
            with open(file_path, 'r') as file:
                lines = file.readlines()
                for line_num, line in enumerate(lines, start=1):
                    match = pattern.search(line)
                    if match:
                        template = match.group(1).strip()

                        if template in hvigor_templates:
                            pass
                        elif template in no_hvigor_templates:
                            error_info = ErrorInfoBuilder() \
                                .set_buggy_file_path(file_entity.file_path) \
                                .set_defect_type("XTS.CHECK.HVIGOR.01") \
                                .set_description("XTS工程必须为hvigor工程") \
                                .set_main_buggy_line(line_num) \
                                .set_main_buggy_code(line.strip()) \
                                .build()

                            utils_data.write_error_to_json_file(error_info)
                            logger.info(json.dumps(error_info, indent=4, ensure_ascii=False))
                            has_error = True
                        else:
                            pass

    if has_error:
        logger.info("hvigor工程检查完成，错误信息已写入xts_result.json")
    else:
        logger.info("hvigor工程检查检查通过")
